package com.neusoft.nepa.controller;

import com.neusoft.nepa.entity.User;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.*;
import java.util.HashMap;

public class ChangePassword {
    @FXML
    private Label label;
    @FXML
    private TextField originPassword;
    @FXML
    private TextField newPassword;
    @FXML
    private TextField confirmPassword;

    @FXML
    public void back(ActionEvent event) throws IOException {
        Stage stage = (Stage) ((javafx.scene.Node) event.getSource()).getScene().getWindow();
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com/neusoft/nepa/view/AdminView.fxml"));
        Parent parent = fxmlLoader.load();
        Scene newScene = new Scene(parent, 960, 540);
        stage.setTitle("NorthEast Software Corporation Public Supervisor Platform Manage System");
        stage.setScene(newScene);
        stage.show();
    }

    public void handle(ActionEvent event) {
        Stage stage = (Stage) label.getScene().getWindow();
        User currentUser = (User) stage.getProperties().get("userInfo");

        // 1. 校验用户信息是否存在
        if (currentUser == null) {
            showAlert("用户信息未获取到", "错误");
            return;
        }
        String currentPhoneNumber = currentUser.getPhoneNumber();
        if (currentPhoneNumber == null || currentPhoneNumber.isEmpty()) {
            showAlert("用户电话号码为空，无法修改密码", "错误");
            return;
        }

        File file = new File("Admin.txt");
        HashMap<String, User> userMap = new HashMap<>();

        // 2. 读取用户数据并校验原密码
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            userMap = (HashMap<String, User>) ois.readObject();

            // 校验原密码是否正确
            if (!originPassword.getText().equals(currentUser.getPasscode())) {
                showAlert("原密码错误", "错误");
                return;
            }

            // 校验新密码是否一致
            if (!newPassword.getText().equals(confirmPassword.getText())) {
                showAlert("新密码与确认密码不一致", "错误");
                return;
            }

            // 检查用户是否存在（键是 phoneNumber）
            if (!userMap.containsKey(currentPhoneNumber)) {
                showAlert("用户不存在于数据文件中", "错误");
                return;
            }

            // 更新密码（通过 phoneNumber 键获取用户）
            User targetUser = userMap.get(currentPhoneNumber);
            targetUser.setPasscode(newPassword.getText());
            userMap.put(currentPhoneNumber, targetUser); // 覆盖更新

        } catch (FileNotFoundException e) {
            showAlert("用户数据文件不存在", "错误");
            return;
        } catch (EOFException e) {
            showAlert("用户数据文件为空，请先注册用户", "错误");
            return;
        } catch (IOException | ClassNotFoundException e) {
            showAlert("读取用户数据失败：" + e.getMessage(), "错误");
            e.printStackTrace();
            return;
        }

        // 3. 写入更新后的用户数据
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
            oos.writeObject(userMap);
            showAlert("密码修改成功", "成功");


            // 加载注册界面的FXML
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/neusoft/nepa/view/AdminLoginView.fxml"));
            Parent fxmlContent = loader.load();

            // 创建背景容器，并将FXML内容添加为子节点
            BackgroundPane backgroundPane = new BackgroundPane();
            backgroundPane.getChildren().add(fxmlContent);
            fxmlContent.setStyle("-fx-background-color: transparent;"); // 确保FXML内容透明

            // 创建新场景，根容器为BackgroundPane
            Scene newScene = new Scene(backgroundPane, 960, 540); // 设置固定尺寸或自适应
            stage.setScene(newScene);
            stage.setTitle("Login");
            stage.show();
        } catch (IOException e) {
            showAlert("保存用户数据失败：" + e.getMessage(), "错误");
            e.printStackTrace();
        }
    }

    private void showAlert(String content, String title) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setContentText(content);
        alert.showAndWait();
    }
}